import tkinter as tk
from tkinter import ttk, messagebox
from .function import (
    load_data,
    sort_students_by_name,
    sort_students_by_total_grade,
    sort_students_by_course_grade,
    search_student_by_id,
    search_course_by_id,
    add_course_to_student,
    remove_course_from_student,
)


# 全局数据存储
students = []
courses = {}
grades = {}


def load_data_ui():
    global students, courses, grades
    try:
        students, courses, grades = load_data()
        label_status.config(text="Data loaded successfully!", fg="green")
    except Exception as e:
        label_status.config(text=f"Error: {e}", fg="red")


def view_students():
    text_output.delete(1.0, tk.END)  # Clear previous content
    if not students:
        text_output.insert(tk.END, "No students available.\n")
        return
    for student in students:
        text_output.insert(
            tk.END,
            f"Username: {student['username']}, Full Name: {student['fullName']}, Age: {student['age']}, School: {student['school']}\n",
        )


def view_courses():
    text_output.delete(1.0, tk.END)  # Clear previous content
    if not courses:
        text_output.insert(tk.END, "No courses available.\n")
        return
    for courseId, course in courses.items():
        text_output.insert(
            tk.END,
            f"Course ID: {course['courseId']}, Title: {course['title']}, Professor: {course['professor']}, Credits: {course['credits']}\n",
        )


def sort_students():
    choice = sort_option.get()  # 获取用户选择的排序方式
    sorted_students = []

    if choice == "name":
        sorted_students = sort_students_by_name(students)
    elif choice == "total_grade":
        sorted_students = sort_students_by_total_grade(students, grades)
    elif choice == "course_grade":
        course_id = entry_sort_course_id.get().strip()  # 获取用户输入的课程 ID
        if not course_id or course_id not in courses:
            text_output.delete(1.0, tk.END)
            text_output.insert(tk.END, "Invalid course ID for sorting.\n")
            return
        sorted_students = sort_students_by_course_grade(students, grades, course_id)

    text_output.delete(1.0, tk.END)  # Clear previous content
    if sorted_students:
        for student in sorted_students:
            text_output.insert(
                tk.END,
                f"Username: {student['username']}, Full Name: {student['fullName']}\n",
            )
    else:
        text_output.insert(tk.END, "No students to sort.\n")


def search_student():
    student_id = entry_search_student_id.get().strip()
    if not student_id:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, "Please enter a valid Student ID.\n")
        return

    student = search_student_by_id(students, student_id)
    text_output.delete(1.0, tk.END)
    if student:
        text_output.insert(tk.END, f"Student Information:\n")
        text_output.insert(tk.END, f"Username: {student['username']}\n")
        text_output.insert(tk.END, f"Full Name: {student['fullName']}\n")
        text_output.insert(tk.END, f"Age: {student['age']}\n")
        text_output.insert(tk.END, f"School: {student['school']}\n")
        text_output.insert(tk.END, f"Interests: {', '.join(student['interests'])}\n")
        text_output.insert(tk.END, f"Followed Courses: {', '.join(student['followed_courses'])}\n")
    else:
        text_output.insert(tk.END, f"No student found with ID: {student_id}\n")


def search_course():
    course_id = entry_search_course_id.get().strip()
    if not course_id:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, "Please enter a valid Course ID.\n")
        return

    course = search_course_by_id(courses, course_id)
    text_output.delete(1.0, tk.END)
    if course:
        text_output.insert(tk.END, f"Course Information:\n")
        text_output.insert(tk.END, f"Course ID: {course['courseId']}\n")
        text_output.insert(tk.END, f"Title: {course['title']}\n")
        text_output.insert(tk.END, f"Department: {course['department']}\n")
        text_output.insert(tk.END, f"Credits: {course['credits']}\n")
        text_output.insert(tk.END, f"Professor: {course['professor']}\n")
        text_output.insert(tk.END, f"Schedule: {course['schedule']}\n")
        text_output.insert(tk.END, f"Description: {course['description']}\n")
        text_output.insert(tk.END, f"Prerequisites: {', '.join(course['prerequisites'])}\n")
    else:
        text_output.insert(tk.END, f"No course found with ID: {course_id}\n")


def add_course():
    student_id = entry_add_course_student_id.get().strip()
    course_id = entry_add_course_course_id.get().strip()

    if not student_id or not course_id:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, "Please enter both Student ID and Course ID.\n")
        return

    student = search_student_by_id(students, student_id)
    if not student:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, f"No student found with ID: {student_id}\n")
        return

    result = add_course_to_student(student, course_id, courses)
    text_output.delete(1.0, tk.END)
    text_output.insert(tk.END, result + "\n")


def remove_course():
    student_id = entry_remove_course_student_id.get().strip()
    course_id = entry_remove_course_course_id.get().strip()

    if not student_id or not course_id:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, "Please enter both Student ID and Course ID.\n")
        return

    student = search_student_by_id(students, student_id)
    if not student:
        text_output.delete(1.0, tk.END)
        text_output.insert(tk.END, f"No student found with ID: {student_id}\n")
        return

    result = remove_course_from_student(student, course_id)
    text_output.delete(1.0, tk.END)
    text_output.insert(tk.END, result + "\n")


def create_ui(root):
    """
    创建用户界面。
    """
    global label_status, entry_sort_course_id, sort_option, text_output, \
           entry_search_student_id, entry_search_course_id, \
           entry_add_course_student_id, entry_add_course_course_id, \
           entry_remove_course_student_id, entry_remove_course_course_id

    # 设置窗口标题和背景颜色
    root.title("Course Management System")
    root.geometry("800x600")
    root.configure(bg="#f0f0f0")

    # Input Frame
    input_frame = tk.Frame(root, bg="#f0f0f0")
    input_frame.pack(side=tk.TOP, pady=10, fill=tk.X)

    # Load Data Button
    tk.Button(
        input_frame,
        text="Load Data",
        command=load_data_ui,
        bg="#9C27B0",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.LEFT, padx=5)

    # View Students Button
    tk.Button(
        input_frame,
        text="View Students",
        command=view_students,
        bg="#03A9F4",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.LEFT, padx=5)

    # View Courses Button
    tk.Button(
        input_frame,
        text="View Courses",
        command=view_courses,
        bg="#FF9800",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.LEFT, padx=5)

    # Search Student Frame
    search_student_frame = tk.Frame(root, bg="#f0f0f0")
    search_student_frame.pack(side=tk.TOP, pady=5, fill=tk.X)

    tk.Label(
        search_student_frame,
        text="Search Student ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_search_student_id = tk.Entry(search_student_frame, font=("Arial", 12))
    entry_search_student_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
    tk.Button(
        search_student_frame,
        text="Search",
        command=search_student,
        bg="#4CAF50",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.RIGHT, padx=5)

    # Search Course Frame
    search_course_frame = tk.Frame(root, bg="#f0f0f0")
    search_course_frame.pack(side=tk.TOP, pady=5, fill=tk.X)

    tk.Label(
        search_course_frame,
        text="Search Course ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_search_course_id = tk.Entry(search_course_frame, font=("Arial", 12))
    entry_search_course_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)
    tk.Button(
        search_course_frame,
        text="Search",
        command=search_course,
        bg="#4CAF50",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.RIGHT, padx=5)

    # Sort Options Frame
    sort_options_frame = tk.Frame(root, bg="#f0f0f0")
    sort_options_frame.pack(side=tk.TOP, pady=5, fill=tk.X)

    tk.Label(
        sort_options_frame,
        text="Sort By:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    sort_option = tk.StringVar(value="name")  # 默认值为 "name"
    tk.Radiobutton(
        sort_options_frame,
        text="Name",
        variable=sort_option,
        value="name",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    tk.Radiobutton(
        sort_options_frame,
        text="Total Grade",
        variable=sort_option,
        value="total_grade",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    tk.Radiobutton(
        sort_options_frame,
        text="Course Grade",
        variable=sort_option,
        value="course_grade",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)

    # Course ID Entry for Sorting by Course Grade
    tk.Label(
        sort_options_frame,
        text="Course ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_sort_course_id = tk.Entry(sort_options_frame, font=("Arial", 12))
    entry_sort_course_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)

    # Sort Button
    tk.Button(
        sort_options_frame,
        text="Sort",
        command=sort_students,
        bg="#4CAF50",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.RIGHT, padx=5)

    # Add Course Frame
    add_course_frame = tk.Frame(root, bg="#f0f0f0")
    add_course_frame.pack(side=tk.TOP, pady=5, fill=tk.X)

    tk.Label(
        add_course_frame,
        text="Add Course to Student",
        font=("Arial", 12, "bold"),
        bg="#f0f0f0",
    ).pack(side=tk.TOP, pady=5)

    tk.Label(
        add_course_frame,
        text="Student ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_add_course_student_id = tk.Entry(add_course_frame, font=("Arial", 12))
    entry_add_course_student_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)

    tk.Label(
        add_course_frame,
        text="Course ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_add_course_course_id = tk.Entry(add_course_frame, font=("Arial", 12))
    entry_add_course_course_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)

    tk.Button(
        add_course_frame,
        text="Add",
        command=add_course,
        bg="#4CAF50",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.RIGHT, padx=5)

    # Remove Course Frame
    remove_course_frame = tk.Frame(root, bg="#f0f0f0")
    remove_course_frame.pack(side=tk.TOP, pady=5, fill=tk.X)

    tk.Label(
        remove_course_frame,
        text="Remove Course from Student",
        font=("Arial", 12, "bold"),
        bg="#f0f0f0",
    ).pack(side=tk.TOP, pady=5)

    tk.Label(
        remove_course_frame,
        text="Student ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_remove_course_student_id = tk.Entry(remove_course_frame, font=("Arial", 12))
    entry_remove_course_student_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)

    tk.Label(
        remove_course_frame,
        text="Course ID:",
        font=("Arial", 12),
        bg="#f0f0f0",
    ).pack(side=tk.LEFT, padx=5)
    entry_remove_course_course_id = tk.Entry(remove_course_frame, font=("Arial", 12))
    entry_remove_course_course_id.pack(side=tk.LEFT, padx=5, expand=True, fill=tk.X)

    tk.Button(
        remove_course_frame,
        text="Remove",
        command=remove_course,
        bg="#FF5252",
        fg="white",
        font=("Arial", 12),
    ).pack(side=tk.RIGHT, padx=5)

    # Status Label
    label_status = tk.Label(
        root, text="", font=("Arial", 12), bg="#f0f0f0"
    )
    label_status.pack(side=tk.BOTTOM, pady=10)

    # Output Text Area with Scrollbar
    output_frame = tk.Frame(root, bg="#f0f0f0")
    output_frame.pack(side=tk.BOTTOM, padx=10, pady=10, fill=tk.BOTH, expand=True)

    text_output = tk.Text(
        output_frame, height=15, width=80, font=("Arial", 12), wrap="word"
    )
    text_output.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    scrollbar = tk.Scrollbar(output_frame, command=text_output.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    text_output.config(yscrollcommand=scrollbar.set)